
from fastapi import Request
from fastapi.responses import Response, JSONResponse

from util.token import Token
from util.log import Log
from common.enum import BaseEnum
from common.config.ReadConfig import WHITE_PATH

# 定义要排除的路径列表
excluded_paths = WHITE_PATH

def check_white_path(path: str):
    try:
        for item in excluded_paths:
            if item[-1] == '*':
                if item[0:-2] in path: # 去掉最后的 '/*'
                    return True
                else:
                    # 要 continue，防止还有路径没判完
                    continue
            else:
                if item == path:
                    return True
        return False
    except Exception as e:
        Log.error('校验 URL 路径')
        return False

async def check_token(request: Request, next):
    try:
        urlPath = request.url.path
        Log.debug(f'request 进入 [check_token] 中间件, 路径为 {urlPath}')
        if check_white_path(urlPath) == False:
            # 验证 token
            token = request.headers.get('token')
            
            if token == None or Token().verify_token(token) == None:
                Log.error('Token 过期或错误, 请检查 Token', token)
                Log.debug('response 离开 [check_token] 中间件')
                return Response(
                    status_code=200,
                    content=str(BaseEnum.TOKEN_INVALID_ERROR),
                    media_type='application/json'
                )
                
        # 放行
        response = await next(request)
        Log.debug('response 离开 [check_token] 中间件')
        return response
    except Exception as e:
        Log.error('校验 token 异常', e)
        return Response(
            status_code=200, 
            content=str(BaseEnum.SERVICE_ERROR),
            media_type='application/json'
        )